#include "herm/base/utils/misc.h"
#include "herm/base/container/buffer.h"
#include "local_session.h"

LocalSession::LocalSession(const herm::LPeerParam& peerParam)
{
	m_buffer = new herm::Buffer(peerParam.bufSize);
	m_tmpBuf = new char[peerParam.bufSize];
	m_msgHandler = nullptr;
	m_peerParam = peerParam;
}

LocalSession::~LocalSession()
{
	delete m_buffer;
	delete[] m_tmpBuf;
}

int LocalSession::GetIndex()
{
	return 0;
}

void LocalSession::RegisterHandler(herm::IMsgHandler* handler)
{
	m_msgHandler = handler;
}

herm::IMsgHandler* LocalSession::GetHandler() const
{
	return m_msgHandler;
}

int LocalSession::Fetch(char* buf, int& len) const
{
	int state = herm::SetState(herm::ST_SUCCESS, 0);
	return CommonHandler::Fetch(state, m_buffer, m_msgHandler, m_peerParam.msgLenFieldSize, m_tmpBuf, buf, len);
}

int LocalSession::Push(const char* buf, int len)
{
	if (len < 0)
        return herm::ST_INVALID_MSG;

//	if (len < 0 || len > m_peerParam->sendTCPBufSize)
//		return herm::ST_INVALID_MSG;

//	if (!herm::IsValidState(m_state))
//		return herm::GetStateType(m_state);

	// PreSend, encryption
	if (m_msgHandler->IsPreSend())
	{
	//	int outLen = m_peerParam->sendTCPBufSize;
		int outLen = 65536;
		int ret = m_msgHandler->PreSend(buf, len, m_tmpBuf, outLen);
		if (ret != herm::ST_SUCCESS)
			return ret;

		if (!m_buffer->Push(m_tmpBuf, outLen))
			return herm::ST_BUFF_FULL;
	}
	else
	{
		// Note, SendQueue->Push will write all data or nothing
		if (!m_buffer->Push(buf, len))
			return herm::ST_BUFF_FULL;
	}

	return herm::ST_SUCCESS;
}

bool LocalSession::IsSendBufferEmpty() const
{
    return m_buffer->Empty();
}
